package com.xbongbong.pro.statistics.strategy.chart.type.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xbongbong.paas.bi.pojo.vo.DataSetResultVO;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.AggTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.pro.bi.commons.helper.CollectionHelper;
import com.xbongbong.pro.bi.commons.pojo.vo.GroupSqlVO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.statistic.constant.ChartConstant;
import com.xbongbong.pro.statistic.help.ChartResultHelp;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.AggsBucketsPojo;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartAnalysisVO;
import com.xbongbong.pro.statistics.help.CkResultHelp;
import com.xbongbong.pro.statistics.help.CommonHelper;
import com.xbongbong.pro.statistics.help.DescribeTableHelper;
import com.xbongbong.pro.statistics.help.DisplayHelper;
import com.xbongbong.pro.statistics.help.InitSqlHelper;
import com.xbongbong.pro.statistics.helper.AggHelper;
import com.xbongbong.pro.statistics.helper.ChartDataSetHelper;
import com.xbongbong.pro.statistics.helper.QueryTableSumHelper;
import com.xbongbong.pro.statistics.pojo.dto.ChartAnalysisDTO;
import com.xbongbong.pro.statistics.pojo.dto.GenerateSqlDTO;
import com.xbongbong.pro.statistics.pojo.vo.GenerateSqlVO;
import com.xbongbong.pro.statistics.service.StarDataService;
import com.xbongbong.pro.statistics.strategy.chart.type.ChartTypeStrategyService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 描述信息
 *
 * @ClassName DataQueryTableStrategyServiceImpl
 * @Author 梁鲁江
 * 创建时间 2022/9/19 9:34
 * 修改时间  2022/9/19 9:34
 **/
@Service
public class DataQueryTableStrategyServiceImpl implements ChartTypeStrategyService {
    @Resource
    private DisplayHelper displayHelper;
    @Resource
    private CkResultHelp ckResultHelp;
    @Resource
    private ChartResultHelp chartResultHelp;
    @Resource
    private DescribeTableHelper describeTableHelper;
    @Resource
    private StarDataService starDataService;
    @Resource
    private ChartDataSetHelper chartDataSetHelper;
    @Resource
    private QueryTableSumHelper queryTableSumHelper;
    @Resource
    private InitSqlHelper initSqlHelper;
    @Resource
    private AggHelper aggHelper;
    private int idCount = 1;

    public Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public ChartAnalysisVO chartAnalysis(ChartAnalysisDTO chartAnalysisDTO) throws XbbException {
        ChartAnalysisVO chartAnalysisVO = new ChartAnalysisVO();
        JSONObject result = new JSONObject();
        ChartEntity chartEntity = chartAnalysisDTO.getChartEntity();
        ChartResultPojo chartResultPojo = chartAnalysisDTO.getChartResultPojo() == null ? new ChartResultPojo() : chartAnalysisDTO.getChartResultPojo();
        PageHelper pageHelper = chartAnalysisDTO.getPageHelper();
        JSONArray tableHeadArr = chartAnalysisDTO.getTableHead();
        Map<JSONObject, FieldAttrPojo> parseAttrMap = chartAnalysisDTO.getParseAttrMap();
        //数据获取
        JSONArray resultArr = chartAnalysisDTO.getResultArray();
        // 无展示字段直接返回
        if (CollectionUtils.isEmpty(chartEntity.getDisplayAttr())) {
            List<Object> list = new ArrayList<>();
            result.put("customTitle", list);
            result.put("customData", list);
            int rowCount = 0;
            result.put("realRowsCount", rowCount);
            pageHelper.setRowsCount(rowCount);
            chartAnalysisVO.setResult(result);
            return chartAnalysisVO;
        }
        /**==============暂时复制过来，可行再合并到一起===================**/
        JSONArray row = new JSONArray();
        JSONArray rowExplain = new JSONArray();
        List<JSONObject> headList = JSONObject.parseArray(tableHeadArr.toJSONString(), JSONObject.class);
        result.put("customTitle", headList);
        //所有列的值map的集合
        List<List<String>> resultCol = new ArrayList<>();
        List<String> dataIdList = new ArrayList<>();
        JSONObject formIdAttr = chartEntity.getFormIdAttr();
        JSONArray filter = chartEntity.getFilter();
        boolean penetrateFlag = ckResultHelp.getPenetrateFlag(filter);
        JSONObject formIdJson = new JSONObject();
        //单表的图没有初始化formIdAttr，穿透的时候会报错
        if(formIdAttr != null){
            for (String s : formIdAttr.keySet()) {
                JSONObject json = formIdAttr.getJSONObject(s);
                formIdJson.put(s,json.getString(FieldTypeEnum.DATAID.getAlias()));
            }
        }
        for (int i = 0; i < tableHeadArr.size(); i++) {
            parseData(chartAnalysisDTO, chartEntity, tableHeadArr, parseAttrMap, resultArr, row, rowExplain, resultCol, dataIdList, formIdAttr, penetrateFlag, i,false);
        }
        List<JSONObject> dataList = JSONObject.parseArray(row.toJSONString(), JSONObject.class);
        JSONArray queryTableResult = chartResultHelp.queryTableAssemble(resultCol, dataList, rowExplain);
        for (int i = 0; i < queryTableResult.size(); i++) {
            JSONObject jsonObject = queryTableResult.getJSONObject(i);
            jsonObject.put("id", dataIdList.get(i));
        }
        result.put("customData", queryTableResult);
        if (dataList.size() > ChartConstant.MAX_SIZE) {
            result.put("customData", queryTableResult.subList(0, ChartConstant.MAX_SIZE));
        }
        /**=================================**/

        
        // 行数
        int rowCount = pageHelper.getRowsCount();
        result.put("realRowsCount", rowCount);
        if (rowCount > ChartConstant.MAX_SIZE) {
            pageHelper.setRowsCount(ChartConstant.MAX_SIZE);
        }
        chartAnalysisVO.setResult(result);
        return chartAnalysisVO;
    }

    /**
     * 查询表解析数据
     * @param baseDTO
     * @param chartEntity 
     * @param tableHeadArr 表头
     * @param parseAttrMap 表头字段和explain的对应
     * @param resultArr 数据
     * @param row   一行数据
     * @param rowExplain  当前行对应的解释
     * @param resultCol  渲染值
     * @param dataIdList  
     * @param formIdAttr
     * @param penetrateFlag  是否穿透
     * @param i  循环标记
     * @param inputPreView  是否是输入节点的预览
     * @throws XbbException
     */
    public void parseData(BaseDTO baseDTO, ChartEntity chartEntity, JSONArray tableHeadArr, Map<JSONObject, FieldAttrPojo> parseAttrMap, JSONArray resultArr, JSONArray row, JSONArray rowExplain, List<List<String>> resultCol, List<String> dataIdList, JSONObject formIdAttr, boolean penetrateFlag, int i,boolean inputPreView) throws XbbException {
        String corpid = baseDTO.getCorpid();
        JSONObject dataObject = tableHeadArr.getJSONObject(i);
        //兼容解析展现字段方法
        FieldAttrPojo fieldAttrPojo = parseAttrMap.get(dataObject);
        //特殊处理address 字段
        Integer type = fieldAttrPojo.getFieldType();
        Integer businessType = fieldAttrPojo.getBusinessType();
        String attr = fieldAttrPojo.getAttr();
        //如果是经销商档案的计算方式
        boolean settlementMethod = DistributorEnum.SETTLEMENT_METHOD.getSaasAttr().equals(fieldAttrPojo.getSaasAttr());
        Long formId = fieldAttrPojo.getFormId();
        JSONObject attrMapping = new JSONObject();
        if (formIdAttr != null && formIdAttr.size() > 0) {
            attrMapping = formIdAttr.getJSONObject(formId.toString());
        }
        String key = dataObject.getString("key");
        String[] keySplit = key.split(XbbConstant.AMPERSAND);
        List<String> values = new ArrayList<>();
        List<String> keyValues = new ArrayList<>();
        JSONObject tableData = new JSONObject();
        Map<String, String> dataIdToEsId = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (int j = 0; j < resultArr.size(); j++) {
            JSONObject singeEntitiesObj = resultArr.getJSONObject(j);
            if(singeEntitiesObj == null){
                continue;
            }
            //ID录入只初始化一次
            if (i == 0) {
                dataIdList.add(FastJsonHelper.getStringOrDefault(singeEntitiesObj, ParameterConstant.ID, ""));
            }
            if (FieldTypeEnum.ADDRESS.equals(FieldTypeEnum.getFieldTypeEnum(type)) && penetrateFlag) {
                String addressList = keySplit[0];
//                String[] addressArray = addressList.split("\\.");
//                        attr = addressArray[0];
                attr = attr.replaceAll("\\.",XbbConstant.SEPARATOR) ;
            }
            // 判断是否是data内字段，虽然字段已被拉宽，但判断方法还是先用es这个
            if (!EsUtil.setInData(type)) {
                //团队特殊处理 需要传dataID 从team中获取团队信息
                String outData = null;
                if(EsHelper.isTeamLogicByFieldType(type, businessType)){
                    if (Objects.nonNull(singeEntitiesObj)){
                        outData = processTeamField(type,keyValues, singeEntitiesObj,false,attr);
                    }
                }else {
                    if(FieldTypeEnum.OWNERID.getType().equals(type)){
                        String team;
                        if(Objects.equals(attr,XbbConstant.OWNER_ID)){
                            team = XbbConstant.MY_TEAM_MAIN +"1";
                        }else {
                            team = attr.replace(FieldTypeEnum.OWNERID.getAlias()+"_",XbbConstant.MY_TEAM_MAIN);
                        }
                        outData =  FastJsonHelper.getStringOrDefault(singeEntitiesObj, team, "");
                    }else if(FieldTypeEnum.COUSERID.getType().equals(type)){
                        //TODO
                    } else {
                        outData =  FastJsonHelper.getStringOrDefault(singeEntitiesObj, attr, "");
                    }
                }
                values.add(outData);
            } else {
                String value = null;
                //type类型为checkbox_group,且isRedundant为0时 为执行人字段 需传dataId作为value
                if (Objects.equals(FieldTypeEnum.CHECKBOX_GROUP.getType(), type) && Objects.equals(0, fieldAttrPojo.getIsRedundant()) && !settlementMethod) {
                    value = FastJsonHelper.getStringOrDefault(singeEntitiesObj, ParameterConstant.ID, "");
                } else {
                   //自定义子表单取值特殊处理
                    if(Objects.equals(FieldTypeEnum.SUB_FORM.getType(), type)){
                        value = FastJsonHelper.getStringOrDefault(singeEntitiesObj,attr, "");
                    }
                    //非自定义子表单取值特殊处理
                   else if (FieldTypeEnum.isSubFormType(type)) {
                        Object subFormVal = singeEntitiesObj.get(attr);
//                        JSONArray subFormJson = subFormVal instanceof JSONArray ? (JSONArray) subFormVal : new JSONArray();
                        JSONArray subFormJson = null;
                        try {
                            subFormJson = JSONArray.parseArray(subFormVal.toString());
                        } catch (Exception e) {
                            subFormJson = new JSONArray();
                        }
                        value = subFormJson.size() == BasicConstant.ZERO ? "" : subFormJson.toJSONString();
                    }
                    //关联字段 回显
                    else if (Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                            || Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_RECEIVER.getType())) {
                        if (Objects.equals(XbbRefTypeEnum.CONTRACT_PERFORMANCE.getCode(),businessType)){//业绩分配关联字段显示特殊处理
                            value = FastJsonHelper.getStringOrDefault(singeEntitiesObj, attr, "");
                        }else {
                            value = FastJsonHelper.getStringOrDefault(singeEntitiesObj, fieldAttrPojo.getLinkedText(), "");
                        }
                    }
                    //客户生日取值特殊处理
                    else if (FieldTypeEnum.BIRTHDAY.getType().equals(type)) {
                            value = describeTableHelper.getBirthday(fieldAttrPojo, singeEntitiesObj, attr);
                    } else if (FieldTypeEnum.ADDRESS.getType().equals(type)) {
                        Object object = singeEntitiesObj.get(attr);
                        if (Objects.isNull(object)) {
                            value = "";
                        } else {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(object.toString());
                                String provinceStr = jsonObject.getString(BusinessConstant.PROVINCE) == null ? "" : jsonObject.getString(BusinessConstant.PROVINCE);
                                String cityStr = jsonObject.getString(BusinessConstant.CITY) == null ? "" : jsonObject.getString(BusinessConstant.CITY);
                                String districtStr = jsonObject.getString(BusinessConstant.DISTRICT) == null ? "" : jsonObject.getString(BusinessConstant.DISTRICT);
                                String addressStr = jsonObject.getString(BusinessConstant.ADDRESS) == null ? "" : jsonObject.getString(BusinessConstant.ADDRESS);
                                value = provinceStr + cityStr + districtStr + addressStr;
                            } catch (Exception e) {
                                value = object.toString();
                            }
                        }
                    }
                    //时间存在num_ 里的处理
                    else if (FieldTypeEnum.DATETIME.getType().equals(type)) {
                        if(attr.contains("num_")){
                            Long intV = FastJsonHelper.getLongOrDefault(singeEntitiesObj, attr, 0L);
                            if (Objects.nonNull(intV)) {
                                value = intV.toString();
                            }
                        }else {
                            value = FastJsonHelper.getStringOrDefault(singeEntitiesObj, attr, "");
                        }
                    }
                    else {
                        if (Objects.isNull(singeEntitiesObj)){continue;}
                        // List Map类型判断
                        if ((singeEntitiesObj.get(attr) instanceof List)) {
                            List list = singeEntitiesObj.getObject(attr, List.class);
                            StringBuilder str = new StringBuilder();
                            if (list != null && list.size() > 0) {
                                for (Object obj : list) {
                                    str.append(obj).append(",");
                                }
                                if (str.length() > 0) {
                                    str.deleteCharAt(str.length() - 1);
                                }
                            }
                            value = str.toString();
                        } else if ((singeEntitiesObj.get(attr) instanceof Map)) {
                            if (type.equals(FieldTypeEnum.ADDRESS.getType())) {
                               
                            } else {
                                value = JSONObject.toJSONString(singeEntitiesObj.get(attr));
                            }
                        } else if(attr.contains("array_")){
                            //数组类型数据的处理
                            value =  singeEntitiesObj.getString(attr);
                            if(StringUtil.isNotEmpty(value)){
                                JSONArray valueArray = JSONArray.parseArray(value);
                                StringBuilder str = new StringBuilder();
                                if (valueArray != null && valueArray.size() > 0) {
                                    for (Object obj : valueArray) {
                                        str.append(obj).append(",");
                                    }
                                    if (str.length() > 0) {
                                        str.deleteCharAt(str.length() - 1);
                                    }
                                }
                                value = str.toString();
                            }else {
                                value = "";
                            }
                        }else {
                            // 特殊处理一下数字类型的值，原因是可能值为int或double类型
                            if (Objects.equals(FieldTypeEnum.NUM.getType(), type)) {
                                Double valueDouble = FastJsonHelper.getDoubleOrDefault(singeEntitiesObj, attr, 0D);
                                if (Objects.nonNull(valueDouble)) {
                                    value = valueDouble.toString();
                                }
                            }else if(Objects.equals(FieldTypeEnum.COMBO_NUM.getType(), type) || Objects.equals(FieldTypeEnum.STAR.getType(), type)  || Objects.equals(FieldTypeEnum.CATEGORY_ID.getType(), type)  || Objects.equals(FieldTypeEnum.WORK_ORDER_NODE_STATUS.getType(), type)) {
                                //逻辑下拉的处理   星级的key应该也是整数 
                                Integer intV = FastJsonHelper.getIntegerOrDefault(singeEntitiesObj, attr, 0);
                                if (Objects.nonNull(intV)) {
                                    value = intV.toString();
                                }
                            } else{
                                value = FastJsonHelper.getStringOrDefault(singeEntitiesObj, attr, "");
                            }
                        }
                    }
                }
                values.add(value);
            }
        }
        Map<String, String> parseDataMap = null;
        if(Objects.equals(FieldTypeEnum.SUB_FORM.getType(), type)){
            if (CollectionsUtil.isNotEmpty(values)) {
                parseDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (String value : values) {
                    parseDataMap.put(value,value);
                }
            }
        }
        else if (FieldTypeEnum.isSubFormType(type)) {
            parseDataMap = chartResultHelp.getSubFormMap(fieldAttrPojo, values, chartEntity, baseDTO);
        } else if (Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                || FieldTypeEnum.BIRTHDAY.getType().equals(type)) {
            parseDataMap = chartResultHelp.assembleDataMap(values);
        } else if (Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.AREA.getType())) {
            parseDataMap = chartResultHelp.distributorAreaMap(chartEntity.getCorpid());
        } else {
            parseDataMap = ckResultHelp.valueListAnalysis(fieldAttrPojo, corpid, values, chartEntity, false,dataIdToEsId,false, baseDTO,null);
        }
        tableData.put(key, parseDataMap);
        rowExplain.add(fieldAttrPojo);
        row.add(tableData);
        //做为二位数组 放入查询表的值
        if(CollectionsUtil.isNotEmpty(keyValues)){
            resultCol.add(keyValues);
        }else {
            resultCol.add(values);
        }
    }

    /**
     * 
     * @param type
     * @param keyValues
     * @param singeEntitiesObj
     * @param single  是否输入节点预览  
     * @param attr
     * @return
     */
    private String processTeamField(Integer type,
                                    List<String> keyValues, JSONObject singeEntitiesObj,
                                    boolean single,String attr) {
        String outData;
        String teamKey = null;
        int teamIdx = 1;
        if (FieldTypeEnum.OWNERID.getType().equals(type)) {
            teamKey = XbbConstant.MY_TEAM_MAIN;
            teamIdx = CommonHelper.getTeamIdx(attr, teamIdx);
        }else if(FieldTypeEnum.COUSERID.getType().equals(type)){
            teamKey = XbbConstant.MY_TEAM;
            teamIdx = CommonHelper.getTeamIdx(attr, teamIdx);
        }
        //int teamIdx = EsUtil.getTeamIdx(chartEntity, formId);
        JSONObject jsonObject = new JSONObject(true);
        JSONArray teamMain = singeEntitiesObj.getJSONArray(teamKey +teamIdx);
        String id;
        if(single){
            /*List<String> idList = singeEntitiesObj.keySet().stream().
                    filter(key -> key.contains(ParameterConstant.ID + XbbConstant.SEPARATOR))
                    .collect(Collectors.toList());
            if (CollectionHelper.isNotEmptyList(idList)){
                id = idList.get(0);
            }else {
            }*/
            id = ParameterConstant.ID;
        }else {
            id = BasicConstant.DATAID+XbbConstant.SEPARATOR+teamIdx;
        }
        String dataIdKey = FastJsonHelper.getStringOrDefault(singeEntitiesObj, id, "");
        if (StringUtils.isEmpty(dataIdKey)){
            dataIdKey = String.valueOf(idCount++);
        }
        jsonObject.put(dataIdKey,teamMain);
        outData = jsonObject.toJSONString();
        keyValues.add(dataIdKey);
        return outData;
    }

    @Override
    public GenerateSqlVO generateSql(GenerateSqlDTO generateSqlDTO) throws XbbException {
        ChartResultPojo chartResultPojo = generateSqlDTO.getChartResultPojo();
        ChartEntity chartEntity = generateSqlDTO.getChartEntity();
        DataSetResultVO dataSetResultVO = chartDataSetHelper.getDataSetParseSql(generateSqlDTO, chartEntity);
        String parseSql = dataSetResultVO.getParseSql();
        GenerateSqlVO generateSqlVO = new GenerateSqlVO();
        generateSqlVO.setJsonStr(dataSetResultVO.getJsonStr());
        List<String> fieldsList = new ArrayList<>();
        //TODO sort 特殊类型需要特殊处理
        Map<String, String> sortMap  = displayHelper.getSortMap(chartEntity,chartResultPojo.getSortMap());
//        {"sort": "asc", "field": "num_5&2", "classify": "displayAttr"}
        Map<String, String> sortFieldMap = new LinkedHashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(sortMap != null && !sortMap.isEmpty()) {
            String field = sortMap.get("field");
            if(StringUtil.isNotEmpty(field)){
                String[] keyArray = field.split(XbbConstant.AMPERSAND);
                String attr = keyArray[0];
                String sort = sortMap.get("sort");
                if(StringUtil.isEmpty(sort)){
                    sort = " asc ";
                }
                sortFieldMap.put(attr,sort);
            }
        }

        JSONArray displayAttr = chartEntity.getDisplayAttr();
        if(CollectionsUtil.isEmpty(displayAttr)){
            return generateSqlVO;
        }
        List<ChartFieldAttrPojo> fieldAttrPojoList = JSONArray.parseArray(displayAttr.toJSONString(), ChartFieldAttrPojo.class);
        JSONArray tableHead = generateSqlDTO.getTableHead();
        Map<JSONObject, FieldAttrPojo> parseAttrMap = generateSqlDTO.getParseAttrMap();
        GroupSqlVO groupSqlVO = new GroupSqlVO();
        List<String> columnAlisaList = new ArrayList<>();
        List<String> subQuerySqlOfCountList = new ArrayList<>();
        for (ChartFieldAttrPojo fieldAttrPojo : fieldAttrPojoList) {
            String attr = fieldAttrPojo.getAttr();
            JSONObject headName = displayHelper.setHeadField(chartEntity.getChartType(), fieldAttrPojo);
            tableHead.add(headName);
            Integer fieldType = fieldAttrPojo.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.LINK_RECEIVER.getType()) || FieldTypeEnum.BIRTHDAY.getType().equals(fieldType)) {
                //生日是两个地方控制的额
                if(FieldTypeEnum.BIRTHDAY.getType().equals(fieldType)){
                    fieldsList.add(attr);
                    columnAlisaList.add(attr);
                }
                String linkedText = fieldAttrPojo.getLinkedText();
                JSONObject linkedJsonObject = fieldAttrPojo.getLinkedAttr();
                if (linkedJsonObject != null) {
                    fieldsList.add(linkedText);
                    columnAlisaList.add(attr);
                }
            }else if (FieldTypeEnum.isSubFormType(fieldAttrPojo.getFieldType())) {
                displayHelper.subFieldItems(fieldAttrPojo, headName);
                //图表中心 数据集展示 需要占位信息 id-formId-businessType-saasMark-attr
                fieldsList.add(attr);
                columnAlisaList.add(attr);
            }else if(Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldAttrPojo.getFieldType())){
                try {
                    AggTypeEnum aggTypeEnum = AggTypeEnum.getByAlias(fieldAttrPojo.getAggType());
                    aggHelper.addComputedField(chartEntity,PaasConstant.LEFT,Maps.newHashMap(),fieldsList, fieldAttrPojo,aggTypeEnum , new ArrayList<>(),subQuerySqlOfCountList,columnAlisaList);
                } catch (XbbException e) {
                    logger.error("查询表计算字段的公式格式有问题", e);
                    throw e;
                }
            } else if ((Objects.equals(FieldTypeEnum.ADDRESS.getType(), fieldType) || Objects.equals(FieldTypeEnum.LOCATION.getType(), fieldType))) {
                if (attr.contains(".")) {
                    String[] keyArray = attr.split("\\.");
                    StringBuilder stringBuilder = new StringBuilder()
                            .append(XbbConstant.GET_JSON_STRING).append(XbbConstant.L_P).append(keyArray[0]).append(XbbConstant.SQL_COMMA).append(XbbConstant.SINGLE_QUOTES).append(XbbConstant.DOLLER).append(XbbConstant.POINT).append(keyArray[1]).append(XbbConstant.SINGLE_QUOTES).append(XbbConstant.R_P);
                    fieldsList.add(stringBuilder.append(XbbConstant.AS).append(attr.replaceAll("\\.", "_")).toString());
                    columnAlisaList.add(attr.replaceAll("\\.", "_"));
                } else {
                    fieldsList.add(attr);
                    columnAlisaList.add(attr);
                }
            } else {
                fieldsList.add(attr);
                columnAlisaList.add(attr);
            }
            parseAttrMap.put(headName, fieldAttrPojo);
        }
        //","分割
        String colums = String.join(XbbConstant.SQL_COMMA, fieldsList);

        groupSqlVO.setSubQuerySqlOfCountList(subQuerySqlOfCountList);
        groupSqlVO.setSummaryColumnAlisa(columnAlisaList);
        initSqlHelper.buildSubColumnOfCount(groupSqlVO,new ArrayList<>(),Boolean.FALSE);

        // fliterMap 默认逻辑在数据集解析的时候处理
        //此处只处理图表中心的筛选和查询条件
        //查询条件和筛选条件放在一起
        String filter = describeTableHelper.filterField(chartEntity);

        //分页
        PageHelper pageHelper;
        if (chartResultPojo.getPage() != null && chartResultPojo.getPageSize() != null) {
            pageHelper = new PageHelper(chartResultPojo.getPage(), chartResultPojo.getPageSize());
        }else {
            pageHelper = new PageHelper(1,PageHelper.PAGE_SIZE);
        }
        //固定最大分页
        if (pageHelper.getCurrentPageNum() * pageHelper.getPageSize() > ChartConstant.MAX_SIZE) {
            pageHelper.setCurrentPageNum(ChartConstant.MAX_SIZE / pageHelper.getPageSize());
        }
        int page = pageHelper.getCurrentPageNum() == null ? 1 : pageHelper.getCurrentPageNum();
        int pageSize =  pageHelper.getPageSize() == null ? 20 :  pageHelper.getPageSize();
        page = Math.max(page, 1);
        int from = (page - 1) * pageSize;
        if (from + pageSize > SizeConstant.PAGE_SIZE) {
            from = 0;
            pageSize = 20;
        }
        pageSize = pageSize == 0 ? 1 : pageSize;
        String sortField = displayHelper.getDsAggSortField(sortFieldMap,groupSqlVO);
        //如果没有手动排序，默认使用id_one排
        if(StringUtil.isEmpty(sortField)){
            sortField = XbbConstant.ID_ONE;
        }
        StringBuffer sql = chartDataSetHelper.tableSqlAppend(parseSql, colums, sortField, filter, pageSize, from, null, false, groupSqlVO);
        generateSqlVO.setStringBufferSql(sql);
        //翻页
        if(Objects.equals(page,1)){
            StringBuffer countSql = chartDataSetHelper.getCommonSql(XbbConstant.COUNT_ALL, parseSql, filter);
            Integer rowsCount = starDataService.countBySql(countSql.toString());
            pageHelper.setRowsCount(rowsCount);
        }else {
            Integer rowsCount = chartResultPojo.getRowsCount();
            //从前端传回，如果没有再去查
            if(rowsCount == null){
                StringBuffer countSql = chartDataSetHelper.getCommonSql(XbbConstant.COUNT_ALL, parseSql, filter);
                rowsCount = starDataService.countBySql(countSql.toString());
            }
            pageHelper.setRowsCount(rowsCount);
        }
        generateSqlVO.setPageHelper(pageHelper);
        if (chartEntity.getSummaryAttr() != null && chartEntity.getSummaryAttr().size() > 0) {
            boolean penetrateFlag = ckResultHelp.getPenetrateFlag(chartEntity.getFilter());
            //第一页且非穿透
            if(Objects.equals(chartResultPojo.getPage(),1) && !penetrateFlag){
                List<AggsBucketsPojo> aggList = queryTableSumHelper.queryTableSum(chartEntity, parseSql, filter,groupSqlVO);
                generateSqlVO.setAggList(aggList);
            }
        }
        return generateSqlVO;
    }





    
}
